package com.tanfuqi.sicent.client.filter

import com.tanfuqi.sicent.client.getSession
import org.apache.mina.core.filterchain.IoFilter
import org.apache.mina.core.filterchain.IoFilterAdapter
import org.apache.mina.core.service.IoConnector
import org.apache.mina.core.session.IoSession
import reactor.core.publisher.Mono
import java.net.SocketAddress

open class BridgeFilter(private val socketAddress: SocketAddress, private val bridgeAddress: SocketAddress) : IoFilterAdapter() {

    override fun messageReceived(nextFilter: IoFilter.NextFilter?, session: IoSession?, message: Any?) {
        val address = when (session?.remoteAddress) {
            socketAddress -> bridgeAddress
            bridgeAddress -> socketAddress
            else -> null
        }
        Mono.justOrEmpty<SocketAddress>(address).flatMap { it ->
            Mono.justOrEmpty<IoConnector>(session?.service as? IoConnector).getSession(it).doOnSuccess {
                it.write(message)
            }
        }.subscribe()

        super.messageReceived(nextFilter, session, message)
    }

}
